package ltd.followkba.task;



import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Random;

import ltd.advskin.MRAM;
import ltd.advskin.MSKIN;
import ltd.advskin.utils.SysUtils;
import ltd.followkba.MAPP;
import ltd.followkba.MDBS;
import ltd.followkba.W;
import ltd.followkba.comment.MUTIL;
import main.CApiUtils;
import main.MAPI;

import static ltd.advskin.MSKIN.MLOGE;
import static ltd.advskin.MSKIN.MSTRING;
import static ltd.advskin.MSKIN.MTOAST;
import static main.MAPI.mMyTools;
import static main.MAPI.mMyUtils;

public class RunUtils {
    // 所有的页面都接受同样的方式打开LOG
    public static boolean logEnable;
    public static void MLOG(String text) {
        if (logEnable) {
            MSTRING("RunUtils "+text);
        }
    }

    public static void saveBDbsAccount(BDbsAccount bDbsAccount){
        MDBS.setBDbsAccount(bDbsAccount);
        TaskEach taskEach = RunUtils.getTaskEach(bDbsAccount);
        if (taskEach != null){
            taskEach.mBDbsAccount = bDbsAccount;
            taskEach.StepTime = bDbsAccount.SetConfig[0] * 1000;         // [0]间隔时间设置
            taskEach.SetChange = true;
//            MLOG(String.format("saveBDbsAccount A %s(%s)", bDbsAccount.LoginFlag, taskEach.mBDbsAccount.LoginFlag));
        }
    }

//    public static void startBDbsAccount(BDbsAccount bDbsAccount){
//        MLOG(String.format("changeUserA2 %s(%s)%s(%s)", bDbsAccount.WorksType, bDbsAccount.AccountName, bDbsAccount.LoginFlag, bDbsAccount.HeadFile));
//        if (MAPP.mBRunRam == null){
//            MAPP.mBRunRam = new ArrayList<>();
//        }
//        synchronized (MAPP.mBRunRam) {
//            int length = MAPP.mtaskEach.size();
//            for (int index = 0; index < length; index++) {
//                BDbsAccount account = MAPP.mtaskEach.get(index).mBDbsAccount;
//                if (account.WorksType == bDbsAccount.WorksType && account.AccountName.endsWith(bDbsAccount.AccountName)) {
//                    MLOG(String.format("重新使用新的对象 %s(%s)", account, bDbsAccount));
//                    bDbsAccount.IndexRun = -1;     // 记录运行的索引
//                    MAPP.mtaskEach.get(index).mBDbsAccount = bDbsAccount;            // 重新使用新的对象
//                    MLOG(String.format("changeUserA5 %s %s %s", bDbsAccount.WorksType, bDbsAccount.AccountName, bDbsAccount.LoginFlag));
//                    return;
//                }
//            }
//        }
//        TaskEach taskEach = new BRunRam();                // 没有找到运行中的任务才新建
//        taskEach.mBDbsAccount = bDbsAccount;
//        taskEach.mLock = new Object();
//        mRankQueue = new ArrayList<>();         // 在榜单之中找到的作品队列
//        mUserQueue = new ArrayList<>();         // 在评论之中找到的用户队列
//        gWorksType = mMyUtils.getWorksType(bDbsAccount.WorksType);
//        StepTime = bDbsAccount.SetConfig[0] * 1000;  // [0]间隔时间设置
////      tring.format("KgAppDbsA bDbsAccount.AccountName %s %s %s", bDbsAccount.AccountName, md5, taskEach.CrcSum5));
//        SuccessQty = 0;
//        NormalCount = taskEach.mBDbsAccount.SuccessQty;
//        NewCount = taskEach.mBDbsAccount.SuccessQty;
//        OldCount = taskEach.mBDbsAccount.SuccessQty;
//        CareCount = taskEach.mBDbsAccount.SuccessQty;
//        GiftCount = taskEach.mBDbsAccount.SuccessQty;
//
//        NormalComment = taskEach.mBDbsAccount.TextComment[W.TEXT_NORMAL].split("\n");          // 标准评论文字
//        NewComment = taskEach.mBDbsAccount.TextComment[W.TEXT_NEW].split("\n");             // 新作品评论文字
//        OldComment = taskEach.mBDbsAccount.TextComment[W.TEXT_OLD].split("\n");             // 旧作品评论文字
//        CareText = taskEach.mBDbsAccount.TextComment[W.TEXT_CARE].split("\n");               // 自动关注文字
//        GiftText = taskEach.mBDbsAccount.TextComment[W.TEXT_GIFT].split("\n");               // 自动礼物文字
//        AdvertText = taskEach.mBDbsAccount.TextComment[W.TEXT_ADVERT].split("\n");             // 广告文字
//
//
//        MAPP.mtaskEach.add(bRunRam);
//        taskEach.mTaskEach = new TaskEach(bRunRam);  // 开始运行线程
//        taskEach.mBDbsAccount.Message = "任务开始运行";
//        taskEach.mBDbsAccount.IndexRun = -1;     // 记录运行的索引
//        MLOG(String.format("changeUserA6 %s %s %s", bDbsAccount.WorksType, bDbsAccount.AccountName, bDbsAccount.LoginFlag));
//    }

    public static String checkAutoCare(TaskEach taskEach){
        if (taskEach.mBDbsAccount.CareSet != null) {           // 设置自动关注
            int[] careSet = taskEach.mBDbsAccount.CareSet;       // 自动关注参数设置 [0]粉丝多于[1]粉丝少于[2]作品多于[3]作品少于
//            MLOG(String.format("CareGiftComment Aa F:%s W:%s %s %s %s %s", taskEach.mBAppUser.FansQty, taskEach.mBAppUser.WorksQty, careSet[0], careSet[1], careSet[2], careSet[3]));
            if (careSet[0] >= 0) {
                if (taskEach.mBAppUser.FansQty < careSet[0]) {    // [0]粉丝多于
                    return null;
                }
            }
            if (careSet[1] >= 0) {
                if (taskEach.mBAppUser.FansQty > careSet[1]) {    // [1]粉丝少于
                    return null;
                }
            }
            if (careSet[2] >= 0) {
                if (taskEach.mBAppUser.WorksQty < careSet[2]) {    // [2]作品多于
                    return null;
                }
            }
            if (careSet[3] >= 0) {
                if (taskEach.mBAppUser.WorksQty > careSet[3]) {    // [1]粉丝少于
                    return null;
                }
            }
            String text = taskEach.CareText[taskEach.CareCount % taskEach.CareText.length];
            MLOG(String.format("CareGiftComment A F:%s W:%s T:%s(%s %s %s %s)", taskEach.mBAppUser.FansQty, taskEach.mBAppUser.WorksQty, text, careSet[0], careSet[1], careSet[2], careSet[3]));
            return text;
        }
        return null;
    }
    public static String checkAutoGift(TaskEach taskEach){
        if (taskEach.mBDbsAccount.GiftSet != null) {           // 设置自动关注
            int[] giftSet = taskEach.mBDbsAccount.GiftSet;       // 自动关注参数设置 [0]粉丝多于[1]粉丝少于[2]作品多于[3]作品少于
//            MLOG(String.format("giftA F:%s W:%s %s %s %s %s", taskEach.mBAppUser.FansQty, taskEach.mBAppUser.WorksQty, giftSet[0], giftSet[1], giftSet[2], giftSet[3]));
            if (giftSet[0] >= 0) {
                if (taskEach.mBAppUser.FansQty < giftSet[0]) {    // [0]粉丝多于
                    return null;
                }
            }
            if (giftSet[1] >= 0) {
                if (taskEach.mBAppUser.FansQty > giftSet[1]) {    // [1]粉丝少于
                    return null;
                }
            }
            if (giftSet[2] >= 0) {
                if (taskEach.mBAppUser.WorksQty < giftSet[2]) {    // [2]作品多于
                    return null;
                }
            }
            if (giftSet[3] >= 0) {
                if (taskEach.mBAppUser.WorksQty > giftSet[3]) {    // [1]粉丝少于
                    return null;
                }
            }
            String text = taskEach.GiftText[taskEach.GiftCount % taskEach.GiftText.length];
//            MLOG(String.format("giftA B F:%s W:%s T:%s(%s %s %s %s)", taskEach.mBAppUser.FansQty, taskEach.mBAppUser.WorksQty, text, giftSet[0], giftSet[1], giftSet[2], giftSet[3]));
            return text;
        }
        return null;
    }

//    public static void stopBDbsAccount(BDbsAccount bDbsAccount){
//        TaskEach taskEach = getTaskEach(bDbsAccount);
//        if (bRunRam != null){
//            taskEach.SetStop = true;
//        }
//    }
    public static List<BUploadPlan> makeRunUploadPlan(List<BUploadPlan> upload, TaskEach taskEach) {
        Collections.sort(upload, new Comparator<BUploadPlan>() {
            public int compare(BUploadPlan info1, BUploadPlan info2) {
                if (info1 != null && info2 != null) {
                    return ((int) (info1.SetTick / 1000) - (int) (info2.SetTick / 1000));  // 升序
                }
                return 0;
            }
        });
        int index = 0;
        while (true) {
//            MLOG(String.format("BUploadPlan C %s %s %s", index, upload.get(index).SetTick, upload.get(index).IsDone));
            if (index < upload.size()) {
                BUploadPlan bUploadPlan = upload.get(index);
                if (bUploadPlan.DoneTick > 0) {
                    upload.remove(bUploadPlan);
                    index = 0;
                } else {
                    ++index;
                }
            }
            if (upload.size() == 0 || index >= upload.size()) {
                break;
            }
        }
        return upload;
    }

    public static TaskEach getTaskEach(BDbsAccount bDbsAccount) {
        if (bDbsAccount != null && MAPP.mTaskEach != null) {
            synchronized (MAPP.mLockTask) {
                int number = MAPP.getWorksTypeIndex(bDbsAccount.WorksType);
                for (int index = 0; index < MAPP.mTaskEach[number].length; index++) {
                    BDbsAccount account = MAPP.mTaskEach[number][index].mBDbsAccount;
                    if (account != null) {
                        if (account.WorksType == bDbsAccount.WorksType && account.AccountName.endsWith(bDbsAccount.AccountName)) {
                            return MAPP.mTaskEach[number][index];
                        }
                    } else {
                        MLOGE(String.format("getTaskEachA %s %s", index, index));
                    }
                }
            }
        }
        return null;
    }

    public static int getIncStep(BDbsAccount bDbsAccount){                        // 获取每步的计数器，每次自动加一
        int step = MDBS.getFreeInt(bDbsAccount, 0, "getIncStep");
        if (step == 0){                                                 // 第一次使用
            step = MAPI.GET_SPEC_WORD_CHECKSUM(bDbsAccount.AccountName.getBytes().length, 0, bDbsAccount.AccountName.getBytes());
        }
        MDBS.setFreeInt(bDbsAccount, 0, "getIncStep", step+1);
        return Math.abs(step);
    }

    public static String getCommentText(String[] params, int counter){
        String text = params[counter % params.length];
        text = text.replace("\r", "");
        StringBuffer outString = new StringBuffer();

        int g4Local_2;
        char g2Local_1;
        int length = text.length();
        int faceStep = counter ^ 0x55555555;
        for (int index = 0; index < length; index++){
            g2Local_1 = text.charAt(index);
            if (g2Local_1 == '='){
//                    MSTRING("评论1："+g4Local_1);
                g4Local_2 = MUTIL.GET_FACE_STRING(faceStep);
                outString.append((char)(g4Local_2 >> 16));
                g4Local_2 = g4Local_2 & 0xffff;
                if (g4Local_2 > 0){
                    outString.append((char)g4Local_2);
                }
                ++faceStep;
            }
            else {
                outString.append(g2Local_1);
            }

        }
        return new String(outString);
    }


    public static boolean addBFileBase(BFileBase[] lists, List<BFileBase> olds, List<BFileBase> blacks){
        int length = (lists != null) ? lists.length : 0;
        int last = olds.size();
        for (int index = 0; index < length; index++) {
            if (!sameBFileBase(lists[index], blacks)) {
                addBFileBase(lists[index], olds);
            }
        }
        return last != olds.size() ? true: false;
    }

//    public static boolean addBFileBase(int userID, int fileID, List<BFileBase> olds){
//        if (!sameBFileBase(userID, fileID, olds)){              // 找到的用户与文件ID不相同
//            BFileBase bFileBase = new BFileBase();
//            bFileBase.UserID = userID;
//            bFileBase.FileID = fileID;
//            olds.add(bFileBase);                               // 在旧列表之中加入
//            return true;
//        }
//        return false;
//    }
    public static boolean addBFileBase(BFileBase bFileBase, List<BFileBase> olds){
        if (!sameBFileBase(bFileBase, olds)){              // 找到的用户与文件ID不相同
            olds.add(bFileBase);                               // 在旧列表之中加入
            return true;
        }
        return false;
    }
//    public static boolean addBFileBase(String userId, String worksId, List<BFileBase> olds){
//        if (!sameBFileBase(userId, worksId, olds)){              // 找到的用户与文件ID不相同
//            BFileBase bFileBase = new BFileBase();
//            bFileBase.UserIdS = userId;
//            bFileBase.WorksIdS = worksId;
//            olds.add(bFileBase);                               // 在旧列表之中加入
//            return true;
//        }
//        return false;
//    }
//    public static boolean sameBFileBase(int userId, int fileId, List<BFileBase> lists){     // 在lists列表找到相同返回true
//        int length = (lists != null) ? lists.size() : 0;
//        for (int index = 0; index < length; index++) {
//            BFileBase bFileBase = lists.get(index);
//            if (userId == bFileBase.UserID){             // 用户ID相同
//                if (bFileBase.FileID == 0 || bFileBase.FileID == fileId) {
//                    return true;                        // FileID为0或者相同都认为是全部相同了
//                }
//            }
//        }
//        return false;                                   // 没有在lists列表之中找到相同
//    }
//    public static boolean sameBFileBase(String userId, String worksId, List<BFileBase> lists){     // 在lists列表找到相同返回true
//        int length = (lists != null) ? lists.size() : 0;
//        for (int index = 0; index < length; index++) {
//            BFileBase bFileBase = lists.get(index);
//            if (userId.equals(bFileBase.UserIdS)){             // 用户ID相同
//                if (worksId == null || bFileBase.WorksIdS == null || worksId.equals(bFileBase.WorksIdS)) {
//                    return true;                        // FileID为0或者相同都认为是全部相同了
//                }
//            }
//        }
//        return false;                                   // 没有在lists列表之中找到相同
//    }
    public static boolean sameBFileBase(BFileBase bFileBase, List<BFileBase> lists){     // 在lists列表找到相同返回true
        int length = (lists != null) ? lists.size() : 0;
            for (int index = 0; index < length; index++) {
                BFileBase base1 = lists.get(index);
                if (bFileBase.UserIdS.equals(base1.UserIdS)){             // 用户ID相同
                    if (bFileBase.WorksIdS == null || base1.WorksIdS == null || bFileBase.WorksIdS.equals(base1.WorksIdS)) {
                        return true;                        // FileID为0或者相同都认为是全部相同了
                    }
                }
            }
        return false;                                   // 没有在lists列表之中找到相同
    }

    public static void loadBlackList(TaskEach taskEach){
//        synchronized (MAPP.mBRunRam) {
        taskEach.mBlackList = new ArrayList<>();
            byte worksType = taskEach.mBDbsAccount.WorksType;
            List<BDbsAccount> accounts = MDBS.getBDbsAccount(worksType);
            int length = (accounts != null) ? accounts.size() : 0;
            for (int index = 0; index < length; index++) {              // 加入自己及相同类型的账号
                BFileBase bFileBase = new BFileBase();
                bFileBase.UserIdS = accounts.get(index).UserIdS;
                taskEach.mBlackList.add(bFileBase);
            }
            int dateTime = mMyUtils.getCurrentDate() >> 16;                 // 只有年月日
            LogTyp[] tabLogTyp = {LogTyp.NORMAL_COMMENT, LogTyp.NEW_COMMENT, LogTyp.OLD_COMMENT, LogTyp.CARE_TEXT, LogTyp.GIFT_TEXT, LogTyp.ADVERT_TEXT};
            for (int index = 0; index < tabLogTyp.length; index++) {
                List<BFileBase> lists = MDBS.getDoneLog(taskEach.mBDbsAccount, tabLogTyp[index]);
                length = (lists != null) ? lists.size() : 0;
                for (int counter = 0; counter < length; counter++) {
                    BFileBase bFileBase = lists.get(counter);
                    if (dateTime != (bFileBase.DateTime >> 16)){           // 不同的年月日
                        MLOGE(String.format("DateTime 删除LOG %s(%s)%s", taskEach.mBDbsAccount.WorksType,taskEach.mBDbsAccount.AccountName, mMyUtils.getSmartDate(bFileBase.DateTime)));
                        MDBS.delDoneLog(taskEach.mBDbsAccount, tabLogTyp[index], bFileBase);
                    }
                }
                if (length > 0) {
                    BFileBase[] bFileBases = MAPI.LISTS_ARRAYS(lists, new BFileBase[lists.size()]);
                    addBFileBase(bFileBases, taskEach.mBlackList, null); // 还在时间内，就需要加入黑名单，不重新刷
                }
            }
//if(taskEach.mBDbsAccount.WorksType==0x00)return;
//            int keepTime = taskEach.mBDbsAccount.SetConfig[2];       // [2]不重新刷的黑名单保持的小时
//            if (keepTime == 0){
//                keepTime = 1;
//            }
//            long keepTick = System.currentTimeMillis();
//            keepTick -= keepTime * (60 * 60 * 1000);
//
//            int delTime = taskEach.mBDbsAccount.SetConfig[3];       // [2]不重新刷的黑名单保持的小时
////delTime=2;
//            if (delTime == 0){
//                delTime = 24;
//            }
//            long delTick = System.currentTimeMillis();
//            delTick -= delTime * (60 * 60 * 1000);
//
//            LogTyp[] tabLogTyp = {LogTyp.NORMAL_COMMENT, LogTyp.NEW_COMMENT, LogTyp.OLD_COMMENT, LogTyp.CARE_TEXT, LogTyp.GIFT_TEXT, LogTyp.ADVERT_TEXT};
////            Calendar calendar = Calendar.getInstance();
//            int delCount = 0;
//            int dateTime = mMyUtils.getCurrentDate();
////            MLOG(String.format("loadBlackListA A SetPause:%s %s %s", System.currentTimeMillis(), keepTick, delTick));
//            for (int index = 0; index < tabLogTyp.length; index++) {
//                List<BFileBase> lists = MDBS.getDoneLog(taskEach.mBDbsAccount, tabLogTyp[index]);
//                length = (lists != null) ? lists.size() : 0;
//                for (int counter = 0; counter< length; counter++) {
//                    BFileBase bFileBase = lists.get(counter);
////                    calendar.setTime(new Date(bFileBase.Tick));
////MDBS.delDoneLog(taskEach.mBDbsAccount, tabLogTyp[index], bFileBase);
//                    if (bFileBase.Tick > delTick) {                         // [3]黑名单最多的数量，会自动删除超出时间的数据
////MLOG(String.format("loadBlackListA G 可以删除了 %s-%s %s:%s", calendar.get(Calendar.MONTH)+1, calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE)));
//                        MDBS.delDoneLog(taskEach.mBDbsAccount, tabLogTyp[index], bFileBase);
//                        ++delCount;
//                    }else if (bFileBase.Tick < keepTick){                         // 还没有超过时间了
////                        MLOG(String.format("loadBlackListA2 还在时间内，不能重新刷 %s-%s %s:%s", calendar.get(Calendar.MONTH)+1, calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE)));
//                        taskEach.mBlackList.add(bFileBase);                  // 还在时间内，就需要加入黑名单，不重新刷
//                    }
//                }
//            }
//            MLOG(String.format("loadBlackListA H %s(%s_%s)size:%s delCount:%s", taskEach.mBDbsAccount.AccountName, keepTime, delTime, taskEach.mBlackList!=null?taskEach.mBlackList.size():0, delCount));
//            MLOG(String.format("loadBlackListA H %s(%s)%s", taskEach.mBDbsAccount.WorksType,taskEach.mBDbsAccount.AccountName,taskEach.mBlackList!=null?taskEach.mBlackList.size():0));
//        }
    }
    public static boolean checkUploadPlan(TaskEach taskEach){
//        synchronized (MAPP.mLockTask) {
            if (taskEach.mBUploadPlan != null) {
                if (System.currentTimeMillis() > taskEach.mBUploadPlan.SetTick) {
                    MLOG("UploadA C");
                    return true;
                }
            } else {
//                if (MDBS.getBUploadPlanSize(taskEach.mBDbsAccount) > 0) {
                    List<BUploadPlan> lists1 = MDBS.getBUploadPlan(taskEach.mBDbsAccount);
                    if (lists1 != null) {
                        List<BUploadPlan> lists2 = makeRunUploadPlan(lists1, taskEach);
                        if (lists2.size() > 0) {
                            taskEach.mBUploadPlan = lists2.get(0);
                            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
                            String text = String.format("将于%s上传%s", sdf.format(taskEach.mBUploadPlan.SetTick), taskEach.mBUploadPlan.WorksName);
                            taskEach.mBDbsAccount.Message = text;
                            MLOG(text);
                            MLOG("UploadA BB "+text);
                            return false;
                        }
                    }
//                }
//                MLOG(String.format("checkUploadPlan B %s", MDBS.getBUploadPlanSize(taskEach.mBDbsAccount)));
            }
//        }
        return false;
    }
    public static int getRandomAbs(int max, Random random){
        if (max < 1){
            max = 1;
        }
        return Math.abs(random.nextInt()) % max;
    }
}
